﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;
using XbsWebAPI.Application.CampRoom.Room.Dtos;
using XbsWebAPI.Application.QueryModel;
using XbsWebAPI.EntityFrameworkCore.Entities;
using XbsWebAPI.Core.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace XbsWebAPI.Application
{
    public class RoomAppService : IRoomAppService
    {
        private readonly IRoomRepository _roomRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<RoomAppService> _logger;

        public RoomAppService(IRoomRepository RoomRepository, IMapper mapper, ILogger<RoomAppService> logger)
        {
            _roomRepository = RoomRepository;
            _mapper = mapper;
            _logger = logger;
        }

        public Task<ResultDto<string>> CreateRoomAsync(CreateRoomDto model)
        {
            var result = new ResultDto<string>();

            try
            {
                var rooms = _roomRepository.Query(a => a.Name == model.Name && a.HouseTypeId == model.HouseTypeId);
                if (rooms != null && rooms.Any())
                {
                    var msg = $"添加失败，该房型下已经有重名了房间名{model.Name},请重新操作";
                    _logger.LogError(msg);
                    result.Code = -1;
                    result.Message = msg;
                    result.Result = "操作失败";
                    return Task.FromResult(result);
                }

                var entity = _mapper.Map<Room>(model);
                _roomRepository.CreateAsync(entity);

                result.Code = 0;
                result.Message = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public Task<ResultDto<string>> EditRoomAsync(EditRoomDto model)
        {
            var result = new ResultDto<string>();
            try
            {
                var rooms = _roomRepository.Query(a => a.Name == model.Name && a.HouseTypeId == model.HouseTypeId);
                if (rooms != null && rooms.Any())
                {
                    var msg = $"更新失败，该房型下已经有重名了房间名{model.Name},请重新操作";
                    _logger.LogError(msg);
                    result.Code = -1;
                    result.Message = msg;
                    result.Result = "操作失败";
                    return Task.FromResult(result);
                }

                var entity = _mapper.Map<Room>(model);
                _roomRepository.UpdateAsync(entity);
                result.Message = "操作成功";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }
            return Task.FromResult(result);
        }

        public ResultDto<GetRoomDto> GetRoomById(Guid id)
        {
            var result = new ResultDto<GetRoomDto>();
            try
            {
                var model = _roomRepository.QueryById(id);
                var entity = _mapper.Map<GetRoomDto>(model);

                result.Code = 0;
                result.Message = "操作成功";
                result.Result = entity;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }

            return result;
        }

        public ResultDto<PageListDto<ListRoomDto>> GetPagedList(QueryRoom query)
        {
            var result = new ResultDto<PageListDto<ListRoomDto>>();

            try
            {
                var Rooms = _roomRepository.AsQueryable();

                if (!string.IsNullOrEmpty(query.Name))
                {
                    Rooms = Rooms.Where(a => a.Name.Contains(query.Name));
                }
                if(query.IsEnabled != null)
                {
                    Rooms = Rooms.Where(a => a.IsEnabled == query.IsEnabled.Value);
                }

                Rooms = Rooms.Include(a => a.HouseType).OrderByDescending(a => a.CreationDate);
                var pagedList = Rooms.ToPagedList(query.PageNumber ?? 1, query.PageSize ?? 10);
                PageListDto<ListRoomDto> pagedDto = new PageListDto<ListRoomDto>()
                {
                    PageNumber = pagedList.PageNumber,
                    PageSize = pagedList.PageSize,
                    HasPreviousPage = pagedList.HasPreviousPage,
                    HasNextPage = pagedList.HasNextPage,
                    TotalCount = pagedList.TotalItemCount
                };
                var dtos = pagedList.Select(e => _mapper.Map<ListRoomDto>(e)).ToList();
                pagedDto.Dtos = dtos;

                result.Code = 0;
                result.Message = "操作成功";
                result.Result = pagedDto;
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = null;
                return result;
            }

            return result;
        }

        public Task<ResultDto<string>> RemoveRoomAsync(Guid id)
        {
            var result = new ResultDto<string>();

            try
            {
                _roomRepository.DeleteAsync(id);
                result.Code = 0;
                result.Message = "操作成功";
                result.Result = "";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }

        public Task<ResultDto<string>> CheckRoomEnable(Guid id, bool isEnable)
        {
            var result = new ResultDto<string>();

            try
            {
                var model = _roomRepository.QueryById(id);


                if (model == null)
                {
                    var msg = $"ID={id}的房间不存在,请重新操作";
                    _logger.LogError(msg);
                    result.Code = -1;
                    result.Message = msg;
                    result.Result = "操作失败";
                    return Task.FromResult(result);
                }

                model.IsEnabled = isEnable;
                _roomRepository.Update(model);
                result.Code = 0;
                result.Message = "操作成功";
                result.Result = "";
            }
            catch (Exception e)
            {
                result.Code = -1;
                result.Message = e.Message;
                result.Result = "操作失败";
                return Task.FromResult(result);
            }

            return Task.FromResult(result);
        }
    }
}
